#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>

#define SA struct sockaddr
#define MONITOR_UNIXUDP "/tmp/monitor.unixudp"
#define QT_UNIXUDP "/tmp/qt.unixudp"

void err_sys(const char *errmsg);

int main(void)
{
    //int ret;
    int sockfd;
    //fd_set rfds;
    //socklen_t len;
    struct sockaddr_un servaddr, cliaddr;
    //char buf[BUFSIZ];
    //ssize_t n;
    //struct timeval timeout;

    if ((sockfd = socket(AF_LOCAL, SOCK_DGRAM, 0)) == -1)
        err_sys("socket");

    bzero(&servaddr, sizeof(servaddr));
    unlink(MONITOR_UNIXUDP);
    servaddr.sun_family = AF_LOCAL;
    strncpy(servaddr.sun_path, MONITOR_UNIXUDP, sizeof(servaddr.sun_path) - 1);

    if (bind(sockfd, (SA *)&servaddr, sizeof(servaddr)) == -1)
        err_sys("bind");

    /* 客户端地址 */
    bzero(&cliaddr, sizeof(cliaddr));
    cliaddr.sun_family = AF_LOCAL;
    strncpy(cliaddr.sun_path, QT_UNIXUDP, sizeof(cliaddr.sun_path) - 1);

    for(;;){
#if 0
        FD_ZERO(&rfds);
        FD_SET(sockfd, &rfds);

        timeout.tv_sec = 3;
        timeout.tv_usec = 0;
        ret = select(sockfd + 1, &rfds, NULL, NULL, &timeout);
        if(ret > 0){
            //len = sizeof(cliaddr);
            //n = recvfrom(sockfd, buf, sizeof(buf), 0, (SA *)&cliaddr, &len);
            //if (n == -1)
             //   err_sys("recvfrom");
            //else
             //   printf("%s\n", buf);

        }else{
            printf("timeout!\n");
        }
#endif
        if (sendto(sockfd, "hello!", 7, 0, (SA *)&cliaddr, sizeof(cliaddr)) != 7)
            perror("sendto");
        usleep((rand() % 10) * 10000);
    }
    exit(0);
}

void err_sys(const char *errmsg)
{
    perror(errmsg);
    exit(1);
}
